package qaz.network;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.Socket;
import java.net.URL;

import android.util.Log;

public class Connection {
	String address;
	String port;
	Socket socket;
	public static Connection con;
	public Connection (String address, String port) throws Exception{
		this.address = address;
		this.port = port;		
		Log.i("newfeed","creating new connection:"+address+"-port:"+port);
		socket = new Socket(address, Integer.parseInt(port));
	}

	public static void init() throws Exception
	{
		String[] host = Connection.getSlaveServer();
		if (host != null)
		{
			con = new Connection(host[0], host[1]);			
		}
	};
	
	
	
	public static String[] getSlaveServer() throws Exception{
		URL url;
		url = new URL("http://192.168.1.104:8080/RQ_SERVER");

		BufferedReader in = new BufferedReader(new InputStreamReader(
				url.openStream()));
		
		String line = null;	
		StringBuilder buff = new StringBuilder();
		while ((line = in.readLine()) != null) {
			buff.append(line);
			Log.i("newfeed", line);
		}
		in.close();
		line = buff.toString();
		if (line.compareTo("NOT_AVAILABLE")!=0)
		return line.split(":");
		else return null;
	}
	
	public static void sendData(String message) throws Exception
	{
		con.send(message);
	}
	
	public void send(String message) throws Exception
	{
		OutputStream out = socket.getOutputStream();
		 PrintWriter output = new PrintWriter(out);
		 output.println(message);
		 output.flush();
		//BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		 //String st = input.readLine();
		 //Log.i("newfeed",st);
		 //socket.close();
	}
	public static String recvData() throws Exception
	{
		return con.recv();
	}
	public String recv()throws Exception{
		BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		//while(input.readLine()!=null)
		 String st = input.readLine();
		 Log.i("newfeed",st);
		 return st;
	}
}
